<template>
  <div class="userUpdate">
    <a-modal
      :visible="showUpdateModal"
      title="修改"
      width="auto"
      :maskClosable="false"
      @cancel="handleCancel"
      @ok="handleOk"
      @close="closeEvent"
      @beforeOpen="beforeOpenEvent"
    >
      <a-form
        ref="formRef"
        :rules="rules"
        :model="form"
        :style="{ width: '600px' }"
      >
        <a-form-item field="userName" label="用户名" validate-trigger="blur">
          <a-input v-model="form.userName" placeholder="请输入用户名..." />
        </a-form-item>
        <a-form-item field="gender" label="性别">
          <a-select v-model="form.gender" placeholder="请选择 ..." allow-clear>
            <a-option :value="0">女</a-option>
            <a-option :value="1">男</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="email" label="邮箱" validate-trigger="blur">
          <a-input v-model="form.email" placeholder="请输入邮箱..." />
        </a-form-item>
        <a-form-item field="phone" label="电话" validate-trigger="blur">
          <a-input v-model="form.phone" placeholder="请输入电话..." />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { effect, ref } from 'vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';

  // eslint-disable-next-line no-undef
  import SysUserUpdateRequest = API.SysUserUpdateRequest;

  const props = defineProps({
    showUpdateModal: Boolean,
    oldData: Object,
  });

  /**
   * 表单
   */
  const generateFormModel = () => {
    return {
      phone: '',
      gender: 0,
      email: '',
      userName: '',
    };
  };

  const formRef = ref();

  const form = ref<SysUserUpdateRequest>(
    generateFormModel as SysUserUpdateRequest
  );

  effect(() => {
    console.log('effect');
  }, props.oldData);
  // 事件
  const emit = defineEmits(['handleUpdateEvent', 'handleUpdateCloseEvent']);

  /**
   * 确认
   */
  const handleOk = () => {
    formRef.value.validate(
      (errors: undefined | Record<string, ValidatedError>) => {
        if (errors === undefined) {
          emit('handleUpdateEvent', form.value);
        }
      }
    );
  };

  /**
   * modal 关闭事件
   * 对话框关闭后（动画结束）触发
   */
  const closeEvent = () => {};

  const beforeOpenEvent = () => {
    console.log('beforeOpenEvent', props.oldData);
    form.value = {
      ...generateFormModel(),
      ...props.oldData,
    };
  };

  /**
   * 取消
   */
  const handleCancel = () => {
    emit('handleUpdateCloseEvent');
  };

  const rules = {
    userName: [
      {
        required: true,
        message: '用户名不能为空',
      },
    ],
    gender: [{ required: true, message: '必须选择' }],
    email: [
      {
        required: true,
        type: 'email',
        message: '邮箱格式错误',
      },
    ],
  };
</script>

<style scoped lang="less">
  .userUpdate {
  }
</style>
